import os

from django.conf import settings
from rest_framework import status

from .serializers import UserSerializer, StudentSerializer, CourseSerializer, GradeSerializer
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from .models import User, Student, Grade, Course

# from django.db.models import Q
# Create your views here.
"""ViewSet视图"""
"""
class UserViewSet(ViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer
"""

"""APIView视图"""


# 登录
class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        if username and password:
            try:
                user = User.objects.get(username=username)
            except User.DoesNotExist:
                return Response({
                    'code': 400,
                    'error': '登录失败',
                    'msg': '用户不存在'
                })
            if user is not None and user.password == password:
                # 登录成功，返回用户信息或其他响应
                return Response({
                    'code': 200,
                    'msg': '登录成功',
                    'data': UserSerializer(user).data
                })
            else:
                # 登录失败，返回错误信息
                return Response({
                    'code': 400,
                    'error': '登录失败',
                    'msg': '密码错误'
                })
        else:
            return Response({'error': '请输入用户名或者密码'}, status=status.HTTP_400_BAD_REQUEST)


# 用户
class UserView(APIView):
    """获取所有用户"""

    def get(self, request):
        search_query = request.query_params.get('search', None)
        if search_query:
            # 如果同时提供了 username 和 email 参数，则进行联合查询
            users = User.objects.filter(username__startswith=search_query)
        else:
            users = User.objects.all()
        serializer = UserSerializer(users, many=True,context={'request': request})
        return Response({
            'code': 200,
            'msg': '获取用户成功',
            'data': serializer.data
        })

    """添加用户"""

    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 200,
                'msg': '添加成功',
                'data': serializer.data
            })
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class UserImageView(APIView):
    def post(self, request, *args, **kwargs):
        user_id = kwargs.get('pk')
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return Response({"error": "User not found"}, status=status.HTTP_404_NOT_FOUND)
        if user.image and user.image.name:
            file_path = os.path.join(settings.MEDIA_ROOT, user.image.name)
            if os.path.exists(file_path):
                os.remove(file_path)

        user.image = None
        user.save()

        serializer = UserSerializer(user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            print('成功')
            return Response({
                'code': 200,
                'message': '上传成功',
                'data': serializer.data
            })
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class UserDetailView(APIView):
    def get(self, request, pk):
        user = User.objects.get(id=pk)
        serializer = UserSerializer(user,context={'request': request})
        return Response({
            'code': 200,
            'message': '获取成功',
            'data': serializer.data
        })

    def put(self, request, pk):
        user = User.objects.get(id=pk)
        serializer = UserSerializer(user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 200,
                'message': '更新成功',
                'data': serializer.data
            })

    def delete(self, request, pk):
        user = User.objects.get(id=pk)
        user.delete()
        return Response({
            'code': 200,
            'message': '删除成功'
        })


"""学生"""


class StudentView(APIView):
    """获取所有学生"""

    def get(self, request):
        students = Student.objects.all()
        serializer = StudentSerializer(students, many=True)
        return Response({
            'code': 200,
            'message': '获取学生成功',
            'data': serializer.data
        })

    """添加学生"""

    def post(self, request):
        serializer = StudentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 200,
                'message': '添加成功',
                'data': serializer.data
            })
        return Response({
            'code': 400,
            'message': '添加失败',
            'data': serializer.errors
        })


class StudentDetailView(APIView):
    def get(self, request, pk):
        student = Student.objects.get(id=pk)
        serializer = StudentSerializer(student)
        return Response({
            'code': 200,
            'message': '获取成功',
            'data': serializer.data
        })

    def put(self, request, pk):
        student = Student.objects.get(id=pk)
        serializer = StudentSerializer(student, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 200,
                'message': '更新成功',
                'data': serializer.data
            })

    def delete(self, request, pk):
        student = Student.objects.get(id=pk)
        student.delete()
        return Response({
            'code': 200,
            'message': '删除成功'
        })


class CourseView(APIView):
    """获取所有课程"""

    def get(self, request):
        search_query = request.GET.get('search', None)
        if search_query:
            courses = Course.objects.filter(course_name__startswith=search_query)
        else:
            courses = Course.objects.all()
        serializer = CourseSerializer(courses, many=True)
        return Response({
            'code': 200,
            'message': '获取课程成功',
            'data': serializer.data
        })

    """添加课程"""

    def post(self, request):
        student_id = request.data.get('student_id')
        course_id = request.data.get('course_id')
        student = Student.objects.get(id=student_id)
        course = Course.objects.get(course_id=course_id)
        if student and course:
            serializer = CourseSerializer(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response({
                    'code': 200,
                    'message': '添加成功',
                    'data': serializer.data
                })
        elif not student:
            return Response({
                'code': 400,
                'message': '学生不存在'
            })
        else:
            return Response({
                'code': 400,
                'message': '课程不存在'
            })
        return Response({
            'code': 400,
            'message': '添加失败',
            'data': serializer.errors
        })


class CourseDetailView(APIView):
    def get(self, request, pk):
        course = Course.objects.get(course_id=pk)
        serializer = CourseSerializer(course)
        return Response({
            'code': 200,
            'message': '获取成功',
            'data': serializer.data
        })

    def put(self, request, pk):
        course = Course.objects.get(course_id=pk)
        serializer = CourseSerializer(course, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 200,
                'message': '更新成功',
                'data': serializer.data
            })
        return Response({
            'code': 400,
            'message': '更新失败',
            'data': serializer.errors
        })

    def delete(self, request, pk):
        course = Course.objects.get(course_id=pk)
        course.delete()
        return Response({
            'code': 200,
            'message': '删除成功'
        })


class GradeView(APIView):
    """获取所有成绩"""

    def get(self, request):
        grades = Grade.objects.all()
        serializer = GradeSerializer(grades, many=True)
        return Response({
            'code': 200,
            'message': '获取成绩成功',
            'data': serializer.data
        })

    """添加成绩"""

    def post(self, request):
        serializer = GradeSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 200,
                'message': '添加成功',
                'data': serializer.data
            })
        return Response({
            'code': 400,
            'message': '添加失败',
            'data': serializer.errors
        })


class GradeDetailView(APIView):
    def get(self, request, pk):
        grade = Grade.objects.get(id=pk)
        serializer = GradeSerializer(grade)
        return Response({
            'code': 200,
            'message': '获取成功',
            'data': serializer.data
        })

    def put(self, request, pk):
        grade = Grade.objects.get(id=pk)
        serializer = GradeSerializer(grade, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response({
                'code': 200,
                'message': '更新成功',
                'data': serializer.data
            })
        return Response({
            'code': 400,
            'message': '更新失败',
            'data': serializer.errors
        })

    def delete(self, request, pk):
        grade = Grade.objects.get(id=pk)
        grade.delete()
        return Response({
            'code': 200,
            'message': '删除成功'
        })
